<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="支出类型" size="small">
            <el-select v-model="searchForm.costType" placeholder="请选择支出类型">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in costTypes"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="项目名称" size="small">
            <el-input v-model="searchForm.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="团队名称" size="small">
            <el-input v-model="searchForm.teamName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="支出对象" size="small">
            <el-input v-model="searchForm.payCompany"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="备注说明" size="small">
            <el-input v-model="searchForm.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col class="datePicker">
          <el-form-item label="时间区间" size="small">
            <el-date-picker type="date" placeholder="选择开始日期" value-format="yyyy-MM-dd" v-model="searchForm.startTimeStr"
            ></el-date-picker>
            <span>-</span>
            <el-date-picker type="date" placeholder="选择结束日期" value-format="yyyy-MM-dd" v-model="searchForm.endTimeStr"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item label="有无合同" size="small">
            <el-switch
              v-model="teamRow.isContractCode"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
              :disabled="isProjectDisabled"
              @change="ContractCodeChange"
            >
            </el-switch>
          </el-form-item>
          <div v-if="teamRow.isContractCode">
            <el-form-item key="contractCode" prop="contractCode" label="合同编号" size="small">
              <el-autocomplete
                v-model="teamRow.contractCode"
                :fetch-suggestions="querySearchProject"
                @select="handleSelectProject"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
            <el-form-item key="projectName" prop="projectName" label="合同项目" size="small">
              <el-autocomplete
                v-model="teamRow.projectName"
                :fetch-suggestions="querySearchProject1"
                @select="handleSelectProject1"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
            <el-form-item v-if="teamRow.teamName" label="所属团队" size="small">
              {{teamRow.teamName}}
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item key="teamName" prop="teamName" label="所属团队" size="small">
              <el-autocomplete
                v-model="teamRow.teamName"
                :fetch-suggestions="querySearchTeam"
                @select="handleSelectTeam"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
          </div>
          <el-form-item prop="costType" label="支出类型" size="small">
            <el-select v-model="teamRow.costType" placeholder="请选择支出类型" @change="costTypeChange($event)">
              <el-option
                v-for="item in costTypes"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="payCompany" label="支出对象" size="small">
            <el-input type="text" v-model="teamRow.payCompany"></el-input>
          </el-form-item>
          <el-form-item prop="payAmount" label="支付金额" size="small">
            <el-input type="number" v-model.number="teamRow.payAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="returnTaxes" label="返税金额" size="small">
            <el-input type="number" v-model.number="teamRow.returnTaxes">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="datePay" label="支付时间" size="small">
            <el-date-picker
              v-model="teamRow.datePay"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="银行名称" size="small">
            {{teamRow.bankName}}
          </el-form-item>
          <el-form-item prop="operator" label="经办人" size="small">
            <el-autocomplete
              v-model="teamRow.operator"
              :fetch-suggestions="querySearchOperator"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="isTender" label="是否投标项目" size="small">
            <el-switch
              v-model="teamRow.isTender"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
      <a target="_blank"
         :href="` /costProject/export?${encodeURI(exportUrl)}`">
        <el-button type="warning" size="small" icon="el-icon-upload2">
          导出
        </el-button>
      </a>
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      :show-summary="true"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="80">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.costId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addCostProject,
    deleteCostProject,
    getCostProjectList,
    selectCostProject,
    selectCostType,
    selectOperator,
    getTeamInfoByProjectNameOrCode,
    updateCostProject,
    selectTeam
  } from '@/api/costproject'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const isTender = {
    props: ['colConfig'],
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <div slot-scope="scope">
          <span  v-if="scope.row[colConfig.prop]">是</span>
          <span  v-else>否</span>
      </div>
  </el-table-column>
  `
  }

  const datePay = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'typeName', label: '支出类型', width: '100', fixed: true },
          { prop: 'projectName', label: '所属项目', width: '350' },
          { prop: 'teamName', label: '所属团队', width: '100' },
          { prop: 'payCompany', label: '支出对象', width: '220' },
          { prop: 'payAmount', label: '支付金额(万元)', width: '100' },
          { prop: 'returnTaxes', label: '返税金额(万元)', width: '100' },
          { prop: 'datePay', label: '支付时间', width: '100', component: datePay },
          { prop: 'bankName', label: '银行名称', width: '150' },
          { prop: 'operator', label: '经办人', width: '100' },
          { prop: 'isTender', label: '是否投标项目', width: '100', component: isTender },
          { prop: 'remark', label: '备注说明', width: '200' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增成本支出',
        dialogType: 0,
        teamRow: {
          returnTaxes: 0,
          payAmount: ''
        },
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          contractCode: [
            { required: true, message: '请输入合同编号', trigger: 'change' }
          ],
          projectName: [
            { required: true, message: '请输入合同项目', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入所属团队', trigger: 'change' }
          ],
          costType: [
            { required: true, message: '请选择支出类型', trigger: 'change' }
          ],
          payCompany: [
            { required: true, message: '请输入支出对象', trigger: 'change' }
          ],
          payAmount: [
            { required: true, message: '请输入支付金额', trigger: 'change' }
          ],
          returnTaxes: [
            { required: true, message: '请输入返税金额', trigger: 'change' }
          ],
          operator: [
            { required: true, message: '请输入经办人', trigger: 'change' }
          ],
          datePay: [
            { required: true, message: '请选择支付日期', trigger: 'change' }
          ],
          isTender: [
            { required: true, message: '请选择是否投标项目', trigger: 'change' }
          ]
        },
        visible: false,
        isProjectDisabled: false,
        exportUrl: '' // 导出参数
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
      this.selectCostType()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getCostProjectList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      selectCostType() {
        selectCostType().then(response => {
          this.costTypes = response.responseBody
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isProjectDisabled = false
        this.dialogTitle = '新增成本支出'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.$set(this.teamRow, 'isContractCode', 1)
        this.$set(this.teamRow, 'costType', '')
        this.$set(this.teamRow, 'datePay', '')
        this.$set(this.teamRow, 'operator', '')
        this.$set(this.teamRow, 'isTender', 0)
        console.log(this.teamRow)
        this.dialogType = 1
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
      },
      editTeam(costId) {
        this.outerVisible = true
        this.isProjectDisabled = true
        this.dialogTitle = '修改成本支出'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          costId: costId
        }
        selectCostProject(params).then(response => {
          let obj = {}
          this.teamRow = Object.assign({}, response.responseBody)
          this.$set(this.teamRow, 'isContractCode', this.teamRow.projectId ? 1 : 0)
          obj = this.costTypes.find((item) => {
            return item.typeId === this.teamRow.costType
          })
          this.$set(this.teamRow, 'costName', obj.typeName)
        })
      },
      submitForm(formName) {
        const params = {
          projectId: this.teamRow.projectId,
          projectName: this.teamRow.projectName,
          contractCode: this.teamRow.contractCode,
          nameOrCode: this.teamRow.nameOrCode,
          teamId: this.teamRow.teamId,
          costType: this.teamRow.costType,
          costName: this.teamRow.costName,
          payCompany: this.teamRow.payCompany,
          payAmount: this.teamRow.payAmount,
          returnTaxes: this.teamRow.returnTaxes,
          datePay: this.teamRow.datePay,
          operator: this.teamRow.operator,
          isTender: this.teamRow.isTender,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (this.teamRow.isContractCode) {
          params.projectId = this.teamRow.projectId
          params.projectName = this.teamRow.projectName
          params.teamId = this.teamRow.teamId
          params.teamName = this.teamRow.teamName
        } else {
          params.teamId = this.teamRow.teamId
          params.teamName = this.teamRow.teamName
        }
        if (!this.dialogType) {
          params.costId = this.teamRow.costId
        }
        if (!this.teamRow.projectId && this.teamRow.isContractCode) {
          this.$message({
            message: '该项目不存在',
            type: 'warning'
          })
        } else if (!this.teamRow.teamId && !this.teamRow.isContractCode) {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        } else {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addCostProject(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updateCostProject(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          costId: scope.row.costId,
          teamId: scope.row.teamId,
          datePay: scope.row.datePay,
          isDel: 1
        }
        deleteCostProject(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      ContractCodeChange() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.$set(this.teamRow, 'teamName', '')
        this.$set(this.teamRow, 'payAmount', '')
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            contractCode: queryString
          }
          getTeamInfoByProjectNameOrCode(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.contractCode
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'contractCode', item.contractCode)
        this.$set(this.teamRow, 'projectName', item.projectName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchProject1(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            projectName: queryString
          }
          getTeamInfoByProjectNameOrCode(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.projectName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject1(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'contractCode', item.contractCode)
        this.$set(this.teamRow, 'projectName', item.projectName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            teamId: this.teamRow.teamId,
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      costTypeChange(event) {
        let obj = {}
        obj = this.costTypes.find(function(item) {
          return item.typeId === event
        })
        this.$set(this.teamRow, 'costName', obj.typeName)
      }
    },
    watch: {
      'searchForm': {
        handler(newValue, oldValue) {
          let exportUrl = ''
          Object.keys(this.searchForm).map((key) => {
            exportUrl += key + '=' + this.searchForm[key] + '&'
          })
          this.exportUrl = exportUrl
        },
        immediate: true,
        deep: true // 深度监听
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
